package com.fourforfo.fourmall.member.service.impl;

import com.fourforfo.common.exception.BizCodeEnum;
import com.fourforfo.common.utils.R;
import com.fourforfo.fourmall.member.entity.MemberLevelEntity;
import com.fourforfo.fourmall.member.exception.DefaultMemberLevelException;
import com.fourforfo.fourmall.member.exception.PhoneExistException;
import com.fourforfo.fourmall.member.exception.UsernameExistException;
import com.fourforfo.fourmall.member.service.MemberLevelService;
import com.fourforfo.fourmall.member.vo.GiteeUserInfoVO;
import com.fourforfo.fourmall.member.vo.MemberLoginVO;
import com.fourforfo.fourmall.member.vo.MemberRegisterVO;
import org.bouncycastle.voms.VOMSAttribute;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fourforfo.common.utils.PageUtils;
import com.fourforfo.common.utils.Query;

import com.fourforfo.fourmall.member.dao.MemberDao;
import com.fourforfo.fourmall.member.entity.MemberEntity;
import com.fourforfo.fourmall.member.service.MemberService;

import javax.xml.crypto.Data;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 注册功能
     * @param registerVO
     */
    @Override
    public void register(MemberRegisterVO registerVO) {
        MemberEntity memberEntity = new MemberEntity();
        //判断该手机号和用户名是否已经被注册
        if(!isExistedPhone(registerVO.getPhone())){
            throw new PhoneExistException();
        }
        if(!isExistedUsername(registerVO.getUsername())){
            throw new UsernameExistException();
        }

        //设置默认等级
        //先获取默认等级
        MemberLevelEntity levelEntity = memberLevelService.getDefaultLevel();
        if(levelEntity==null){
            log.error("请设置默认会员等级！");
            throw new DefaultMemberLevelException();
        }
        memberEntity.setLevelId(levelEntity.getId());

        //设置
        memberEntity.setMobile(registerVO.getPhone());
        memberEntity.setUsername(registerVO.getUsername());
        memberEntity.setNickname(registerVO.getUsername());
        memberEntity.setCreateTime(new Date());
        //使用BCryptPasswordEncoder加密密码
        BCryptPasswordEncoder cryptPasswordEncoder = new BCryptPasswordEncoder();
        String cryptPassword = cryptPasswordEncoder.encode(registerVO.getPassword());
        memberEntity.setPassword(cryptPassword);

        baseMapper.insert(memberEntity);
    }

    //判断该手机号是否已经被注册
    @Override
    public boolean isExistedPhone(String phone) {
        int count = count(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        return count==0?true:false;
    }

    //判断该用户名是否已经被注册
    @Override
    public boolean isExistedUsername(String username) {
        int count = count(new QueryWrapper<MemberEntity>().eq("username",username));
        return count==0?true:false;
    }

    /**
     * 接受用户名密码，验证是否正确
     * @param loginVO
     * @return
     */
    @Override
    public MemberEntity login(MemberLoginVO loginVO) {
        /**
         * 查询数据库中用户名或者手机号等于这个登录名的数据
         * 注意：注册时需要对用户名作限制，不能是纯数字，
         *      不然可能出现某人手机号与另一人用户名一样的情况，
         *      那样的话按如上查询条件可能出现查出两天用户信息
         */
        MemberEntity entity = getOne(new QueryWrapper<MemberEntity>()
                .eq("username",loginVO.getLoginName())
                .or().eq("mobile",loginVO.getLoginName()));
        if(entity==null)
            return null;

        boolean isExisted = loginVO.getLoginName().equals(entity.getUsername())||loginVO.getLoginName().equals(entity.getMobile());
        if(isExisted){
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            if(encoder.matches(loginVO.getPassword(),entity.getPassword())){
                return entity;
            }
        }
        return null;
    }

    /**
     * 根据Gitee的信息进行社交登录
     * @param userInfoVO
     * @return
     */
    @Override
    public MemberEntity login(GiteeUserInfoVO userInfoVO) {
        //判断当然社交用户的giteeId是否已经在数据库中了
        MemberEntity memberEntity = this.getOne(new QueryWrapper<MemberEntity>().eq("gitee_id", userInfoVO.getId()));
        if(memberEntity!=null){
            //说明已经被注册过了

            return memberEntity;
        }else{
            //没有查到就需要重新注册
            memberEntity = new MemberEntity();
            //giteeId是当前gitee登录用户的唯一id
            memberEntity.setGiteeId(userInfoVO.getId()+"");

            memberEntity.setNickname(userInfoVO.getName());
            memberEntity.setEmail(userInfoVO.getEmail());
            memberEntity.setCreateTime(new Date());

            this.save(memberEntity);
            return memberEntity;

        }
    }

}